import axios from "axios";
import store from '@/store'
import router from '@/router'

export function request(config) {
    const httpClient = axios.create({
        baseURL: "http://172.30.252.43:21021",
        timeout: 30 * 1000,
        isRetryRequest: false
    })
    httpClient.interceptors.request.use(config => {
        if (store.getters.getToken) {
            config.headers['Authorization'] = "Bearer " + store.getters.getToken
        }
        return config;
    }, (error) => {
        return Promise.reject(error)
    });

    httpClient.interceptors.response.use(
        res => {
            return Promise.resolve(res.data)
        },
        error => {
            if (error && error.response) {
                switch (error.response.status) {
                    case 400:
                        error.message = '无效的请求'
                        break;
                    case 401:
                        store.commit("clearToken");
                        error.message = '未授权，请重新登录'
                        router.replace("/401");
                        break;
                    case 404:
                        error.message = '未找到该资源'
                        router.replace("/404");
                        break;
                    case 405:
                        error.message = '请求的方法不被允许，请检查请求Method类型'
                        break;
                    case 500:
                        error.message = '服务端内部异常'
                        break;
                    default:
                        console.log("其他异常");
                        break;
                }
            }
            else {
                error.message = '请求出错，请检查网络'
            }
            return Promise.reject(error)
        });
    return httpClient(config);
}